<template>
  <div class="app-container">
    <!-- 桌面端布局 -->
    <el-row :gutter="10" v-if="!isMobile">
      <el-col :span="24">
        <div class="course_content">
          <el-row type="flex" justify="around" style="width: 100%">
            <el-col :span="20">
              <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
                <el-form-item label="关联考试" prop="exam">
                  <el-select v-model="queryParams.exam" placeholder="请选择.." clearable filterable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in examOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="参考人员" prop="user">
                  <el-select v-model="queryParams.user" placeholder="请选择.." filterable clearable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in userOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="考试状态" prop="state">
                  <el-select v-model="queryParams.state" placeholder="请选择.." clearable size="small" @change="handleQuery">
                    <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>
                <el-form-item label="是否交卷" prop="is_submited">
                  <el-select v-model="queryParams.is_submited" placeholder="请选择.." clearable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in submitedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>
                <el-form-item label="是否阅卷" prop="is_marked">
                  <el-select v-model="queryParams.is_marked" placeholder="请选择.." clearable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in markedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>
                <el-form-item label="考试结果" prop="is_passed">
                  <el-select v-model="queryParams.is_passed" placeholder="请选择.." clearable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in passedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" size="mini" @click="handleQuery" :style="{
                    backgroundColor: theme,
                    borderColor: theme
                  }">搜索</el-button>
                  <el-button size="mini" @click="resetQuery">清空</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-table :data="List" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }">
            <el-table-column label="考试名称" prop="name"></el-table-column>
            <el-table-column label="考生" >
              <template slot-scope="scope" >
               <span v-if="scope.row.user&&scope.row.user.name">{{ scope.row.user.name }}</span>
               <span v-else>暂无</span>
              </template>
            </el-table-column>
            <el-table-column label="考试得分">
              <template slot-scope="scope">
                <span :style="scope.row.score >= scope.row.qualify_score ? { color: theme, }
                  : '{}'" v-show="scope.row.question !== undefined && scope.row.question.length > 0">{{
    (scope.row.score * (100 / scope.row.question.length)).toFixed(2) }}</span></template>
            </el-table-column>
            <el-table-column label="及格分" prop="qualify_score"></el-table-column>
            <el-table-column label="试卷满分">{{ 100 }}</el-table-column>
            <el-table-column label="考试结果" prop="is_passed" :formatter="resultFormatter"></el-table-column>
            <el-table-column label="考试时间" width="200">
              <template slot-scope="scope">
                <div class="info-item time-item">
                  <span class="label">考试开始：</span>
                  <span class="value time-value">{{ scope.row.start_time || '暂无' }}</span>
                </div>
                <div class="info-item time-item">
                  <span class="label">考试结束：</span>
                  <span class="value time-value">{{ scope.row.end_time || '暂无' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="考试状态">
              <template slot-scope="scope">
                <span v-if="scope.row.state == 2 && scope.row.is_submited == false">缺考</span>
                <span v-else>{{ scope.row.state_name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="答题详情" width="100">
              <template slot-scope="scope">
                <el-button icon="el-icon-caret-right" type="primary" size="mini" @click="handlePaperDetail(scope.row)"
                  v-show="(scope.row.state == 2 && scope.row.is_submited !== false) || scope.row.is_submited == true"
                  :style="{
                    backgroundColor: theme,
                    borderColor: theme,
                    fontWeight: 'bold'
                  }" v-hasPermi="['exam:results:query']">
                  查阅</el-button>


              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size"
            @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    
    <!-- 移动端布局 -->
    <template v-if="isMobile">
      <div class="course_content">
        <!-- 移动端搜索表单 -->
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" class="mobile-form">
          <el-form-item label="关联考试" prop="exam">
            <el-select v-model="queryParams.exam" placeholder="请选择.." clearable filterable size="small"
              @change="handleQuery">
              <el-option v-for="dict in examOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="参考人员" prop="user">
            <el-select v-model="queryParams.user" placeholder="请选择.." filterable clearable size="small"
              @change="handleQuery">
              <el-option v-for="dict in userOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="考试状态" prop="state">
            <el-select v-model="queryParams.state" placeholder="请选择.." clearable size="small" @change="handleQuery">
              <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否交卷" prop="is_submited">
            <el-select v-model="queryParams.is_submited" placeholder="请选择.." clearable size="small"
              @change="handleQuery">
              <el-option v-for="dict in submitedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否阅卷" prop="is_marked">
            <el-select v-model="queryParams.is_marked" placeholder="请选择.." clearable size="small"
              @change="handleQuery">
              <el-option v-for="dict in markedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="考试结果" prop="is_passed">
            <el-select v-model="queryParams.is_passed" placeholder="请选择.." clearable size="small"
              @change="handleQuery">
              <el-option v-for="dict in passedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          
          <el-form-item class="form-buttons">
            <el-button type="primary" size="small" @click="handleQuery" :style="{
              backgroundColor: theme,
              borderColor: theme,
              width: '48%'
            }">搜索</el-button>
            <el-button size="small" @click="resetQuery" style="width: 48%; float: right;">清空</el-button>
          </el-form-item>
        </el-form>
          
        <!-- 移动端工具栏 -->
        <el-row :gutter="10" class="mb8 mobile-toolbar">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        
        <!-- 移动端卡片视图 -->
        <div class="mobile-card-view show-all-content">
          <div v-if="List.length === 0" class="empty-data">
            <i class="el-icon-document"></i>
            <p>暂无数据</p>
          </div>
          
          <el-card v-for="(item, index) in List" :key="index" class="mobile-card" shadow="hover">
            <div slot="header" class="card-header">
              <div class="card-title" :style="{ color: theme }">{{ item.name }}</div>
              <div class="card-actions">
                <el-button 
                  v-hasPermi="['exam:results:query']"
                  v-if="(item.state == 2 && item.is_submited !== false) || item.is_submited == true"
                  size="mini"
                  type="text"
                  :style="{ color: theme }"
                  @click="handlePaperDetail(item)">
                  <i class="el-icon-caret-right"></i>
                </el-button>
              </div>
            </div>
            <div class="card-content">
              <div class="info-list">
                <!-- 基本信息 -->
                <div class="info-group">
                  <div class="info-item">
                    <span class="label">考生：</span>
                    <span class="value" v-if="item.user && item.user.name">{{ item.user.name }}</span>
                    <span class="value" v-else>暂无</span>
                  </div>
                  <div class="info-item" v-if="item.question !== undefined && item.question.length > 0">
                    <span class="label">考试得分：</span>
                    <span class="value" :style="item.score >= item.qualify_score ? { color: theme } : '{}'">
                      {{ (item.score * (100 / item.question.length)).toFixed(2) }}
                    </span>
                  </div>
                  <div class="info-item">
                    <span class="label">及格分：</span>
                    <span class="value">{{ item.qualify_score }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">试卷满分：</span>
                    <span class="value">100</span>
                  </div>
                  <div class="info-item">
                    <span class="label">考试结果：</span>
                    <span class="value">{{ resultFormatter(item) }}</span>
                  </div>
                  
                </div>
                
                
                <!-- 时间信息，使用特殊样式 -->
                <div class="time-group">
            
                  <div class="info-item time-item">
                    <span class="label">考试结束：</span>
                    <span class="value time-value">{{ item.end_time || '暂无' }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">考试状态：</span>
                    <span class="value" v-if="item.state == 2 && item.is_submited == false">缺考</span>
                    <span class="value" v-else>{{ item.state_name }}</span>
                  </div>
                </div>
              </div>
              
              <!-- 答题详情按钮 -->
              <div class="card-actions-footer" 
                v-if="(item.state == 2 && item.is_submited !== false) || item.is_submited == true">
                <el-button 
                  type="primary"
                  size="mini"
                  icon="el-icon-caret-right"
                  @click="handlePaperDetail(item)"
                  :style="{
                    backgroundColor: theme,
                    borderColor: theme,
                    fontWeight: 'bold',
                    margin: '10px auto 0',
                    display: 'block',
                    width: 'auto'
                  }"
                  v-hasPermi="['exam:results:query']">
                  查阅
                </el-button>
              </div>
            </div>
          </el-card>
          
          <!-- 移动端分页 -->
          <div class="mobile-pagination" v-if="total > 0">
            <div class="mobile-pagination-wrapper">
              <!-- 第一行：总数和每页条数 -->
              <div class="pagination-row top-row">
                <span class="el-pagination__total">共 {{ total }} 条</span>
                <el-select 
                  v-model="queryParams.page_size" 
                  size="mini" 
                  class="el-pagination__sizes"
                  @change="handleSizeChange">
                  <el-option
                    v-for="item in [10, 20, 30, 50]"
                    :key="item"
                    :label="`${item}条/页`"
                    :value="item">
                  </el-option>
                </el-select>
              </div>
              
              <!-- 第二行：页码导航 -->
              <div class="pagination-row bottom-row">
                <el-pagination
                  background
                  @current-change="handleCurrentChange"
                  :current-page="queryParams.page"
                  :page-size="queryParams.page_size"
                  layout="prev, pager, next, jumper"
                  :total="total">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import { markingExam } from "@/api/vadmin/exam/making";
import { getExam } from "@/api/vadmin/exam/exam";
import { paperList } from "@/api/vadmin/exam/exam";
import { listUser } from "@/api/vadmin/permission/user";
import CourseTree from "@/components/CourseTree";
import "@/assets/styles/mobile/exam.scss";

export default {
  name: "results",
  components: { CourseTree },
  data() {
    return {
      title: "考试分类",
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      courseList: null,
      form: {},
      queryParams: {
        // courseId: "",
        is_marked: "",
        page: 1,
        page_size: 10,
        user:this.$store.state.user.id
      },
      // 阅卷状态
      options: [
        { value: true, label: "已阅卷" },
        { value: false, label: "待阅卷" },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      stateOptions: [
        {
          dictValue: 0,
          dictLabel: "未开始",
        },
        {
          dictValue: 1,
          dictLabel: "进行中",
        },
        {
          dictValue: 2,
          dictLabel: "已结束",
        },
      ],
      submitedOptions: [
        {
          dictValue: true,
          dictLabel: "是",
        },
        {
          dictValue: false,
          dictLabel: "否",
        },
      ],
      markedOptions: [
        {
          dictValue: true,
          dictLabel: "是",
        },
        {
          dictValue: false,
          dictLabel: "否",
        },
      ],
      passedOptions: [
        {
          dictValue: true,
          dictLabel: "合格",
        },
        {
          dictValue: false,
          dictLabel: "不合格",
        },
      ],
      userOptions: [],
      examOptions: [],
      List: [],
      courseOptions: [],
      courseName: undefined,
      intervalId: null,
      isMobile: false,
      mediaQueryList: null,
      selectedResult: null
    };
  },
  computed: {
    ...mapState(["settings","id"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
    id() {
      return this.$store.state.user.id;
    }
  },
  filters: {
    subFilter(value) {
      if (value) {
        return "已交卷";
      } else {
        return "未交卷";
      }
    },
    resultFilter(value) {
      return value ? "合格" : "不合格";
    }
  },

  created() {
    this.getBasicData();
    if (this.$route.query.exam) {
      this.queryParams.exam = Number(this.$route.query.exam);
      this.getList();
    } else {
      this.getList();
    }
  },

  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },

  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      paperList(this.queryParams).then((response) => {
        this.List = response.results;
        
        // 确保时间字段有值
        if (this.List && this.List.length > 0) {
          this.List = this.List.map(item => {
            return {
              ...item,
              start_time: item.start_time || '暂无数据',
              end_time: item.end_time || '暂无数据'
            };
          });
          console.log('处理后的第一条数据:', this.List[0]);
        }
        
        this.total = response.count;
        this.loading = false;
        // 添加调试代码
        if (this.List && this.List.length > 0) {
          console.log('第一条数据:', this.List[0]);
          console.log('start_time:', this.List[0].start_time);
          console.log('end_time:', this.List[0].end_time);
        }
      });
    },
    getBasicData() {
      getExam({ page_size: 10000, page: 1 }).then((response) => {
        this.examOptions = response.results;
      });

      listUser({ page_size: 10000, page: 1 }).then((response) => {
        this.userOptions = response.results;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.name_wd = "";
      this.queryParams.content_wd = "";
      this.resetForm("queryForm");
      // this.$refs['queryForm'].resetFields();
      this.handleQuery();
    },
    /*去考试 */
    handlePaperDetail(row) {
      this.$router.push({
        name: "paperDetail",
        params: { id: row.id },
      });
    },
    /*新增考试 */
    handleAdd() {
      this.$router.push({ name: "Newexam" });
    },
    /*修改试卷 */
    handleUpdate(row) {
      this.$router.push({ name: "Newexam", params: { id: row.id } });
    },
    resultFormatter(value) {
      if (value.is_passed == true) {
        return "合格";
      } else if (value.is_passed == false) {
        return "不合格";
      }
    },
    handleSizeChange(size) {
      this.queryParams.page_size = size;
      this.getList();
    },
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getList();
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
  padding: 0;
}

.form-buttons {
  display: flex;
  justify-content: space-between;
  
  .el-button + .el-button {
    margin-left: 0;
  }
}

/* 移动端样式优化 */
@media screen and (max-width: 767px) {
  /* 移动端搜索表单样式 */
  .mobile-form {
    padding: 10px;
    
    .el-form-item {
      margin-bottom: 10px;
      width: 100%;
      
      .el-form-item__content {
        width: 100%;
        
        .el-select {
          width: 100%;
        }
      }
    }
    
    .form-buttons {
      margin-top: 10px;
      
      .el-button {
        width: 48%;
        margin: 0;
      }
    }
  }
  
  /* 移动端工具栏样式 */
  .mobile-toolbar {
    margin-bottom: 10px !important;
    
    .el-row {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 8px;
      padding: 0 10px;
      
      .el-button {
        margin: 0;
        padding: 7px 12px;
        font-size: 12px;
        height: auto;
        line-height: 1.2;
      }
      
      .el-button-group {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .el-button {
          margin: 0;
        }
      }
    }
  }
  
  /* 移动端卡片样式 */
  .mobile-card-view {
    margin-top: 15px;
    padding: 0 10px;
    
    .mobile-card {
      margin-bottom: 15px;
      border-radius: 8px;
      overflow: hidden;
      
      .card-header {
        padding: 12px;
        border-bottom: 1px solid #eee;
        
        .card-title {
          font-size: 16px;
          font-weight: 500;
        }
      }
      
      .card-content {
        padding: 12px;
        
        .info-list {
          .info-group, .time-group {
            margin-bottom: 15px;
          }
          
          .time-group {
            background-color: #f9f9f9;
            padding: 10px;
            border-radius: 4px;
            border-left: 3px solid #ddd;
          }
          
          .info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            
            .label {
              color: #666;
              min-width: 80px;
            }
            
            .value {
              flex: 1;
              text-align: right;
              
              &.time-value {
                color: #333;
              }
            }
          }
        }
        
        .card-actions-footer {
          margin-top: 15px;
          text-align: center;
          
          .el-button {
            width: 100%;
            margin: 0;
          }
        }
      }
    }
  }
  
  /* 移动端分页样式 */
  .mobile-pagination {
    margin-top: 20px;
    padding: 0 10px;
    
    .mobile-pagination-wrapper {
      background: #fff;
      padding: 10px;
      border-radius: 4px;
      
      .pagination-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }
}

/* 桌面端时间字段调整 */
.el-table {
  .info-item.time-item {
    text-align: left;
    margin-bottom: 5px;
    
    .label {
      display: inline-block;
      width: 70px;
      text-align: right;
      margin-right: 5px;
    }
    
    .time-value {
      display: inline-block;
    }
  }
}
</style>